<template>
  <div class="page_content">
    <div v-if="isPageLoading" class="page_loading fixed">
      <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
    </div>
    <header>
      <van-nav-bar class="main_header" title="中国跆拳道级段位信息">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
        <template #right>
          <span @click="submitRefresh">确定</span>
        </template>
      </van-nav-bar>
    </header>
    <div class="main_content">
      <van-form ref="vo" label-width="115px" label-align="left" :scroll-to-error="true">
        <van-field
          name="ctaBeltLevel"
          label="中国跆协级位"
          placeholder="请选择中国跆协级位"
          right-icon="arrow"
          :value="findDictDataByCode('dictCtaBeltLevel', vo.ctaBeltLevel).value"
          :rules="ModTkwChiDanVO_Rules.ctaBeltLevel"
          @click="openSelectBox('ctaBeltLevel')"
        />
        <van-field
          name="ctaBeltDuan"
          label="中国跆协段位"
          placeholder="请选择中国跆协段位"
          right-icon="arrow"
          :value="findDictDataByCode('dictCtaBeltDuan', vo.ctaBeltDuan).value"
          :rules="ModTkwChiDanVO_Rules.ctaBeltDuan"
          @click="openSelectBox('ctaBeltDuan')"
        />
        <van-field
          v-model.trim="vo.ctaBeltLevelId"
          label="中国跆协级位编号"
          name="ctaBeltLevelId"
          :required="!vo.ctaBeltLevel ? false : true"
          clearable
          :rules="!vo.ctaBeltLevel ? [] : ModTkwChiDanVO_Rules.ctaBeltLevelId"
        />
        <van-field
          v-model.trim="vo.ctaBeltDuanId"
          label="中国跆协段位编号"
          name="ctaBeltDuanId"
          :required="!vo.ctaBeltDuan ? false : true"
          clearable
          :rules="ModTkwChiDanVO_Rules.ctaBeltDuanId"
        />
        <van-field
          label="中国跆协级位照片"
          name="ctaBeltLevelImageUrl1"
          :required="!vo.ctaBeltLevel ? false : true"
          input-align="right"
          right-icon="arrow"
          :style="{ 'line-height': vo.ctaBeltLevelImageUrl1 ? '50px' : '24px' }"
          :rules="!vo.ctaBeltLevel ? [] : ModTkwChiDanVO_Rules.ctaBeltLevelImageUrl1"
          @click="openChangeImg('imgListLevel')"
        >
          <template #input>
            <div v-for="(item, index) in 6" :key="index">
              <van-image
                width="25"
                height="25"
                class="gl_mr_5"
                :rules="!vo.ctaBeltLevel ? [] : ModTkwChiDanVO_Rules.ctaBeltLevelImageUrl1"
                :src="getStaticFileUrl(imgListLevel[index])"
                @click="imagePreview(imgListLevel[index])"
              />
            </div>
          </template>
        </van-field>
        <van-field
          label="中国跆协段位照片"
          name="ctaBeltDuanImageUrl1"
          :required="!vo.ctaBeltDuan ? false : true"
          input-align="right"
          right-icon="arrow"
          :style="{ 'line-height': vo.ctaBeltDuanImageUrl1 ? '50px' : '24px' }"
          @click="openChangeImg('imgListDuan')"
        >
          <template #input>
            <div v-for="(item, index) in 6" :key="index">
              <van-image
                width="25"
                height="25"
                class="gl_mr_5"
                :rules="!vo.ctaBeltLevel ? [] : ModTkwChiDanVO_Rules.ctaBeltLevelImageUrl1"
                :src="getStaticFileUrl(imgListDuan[index])"
                @click="imagePreview(imgListDuan[index])"
              />
            </div>
          </template>
        </van-field>
        <!-- 级段位照片 -->
        <van-popup
          v-model="logoDialog"
          get-container="#app"
          position="right"
          :style="{ width: '100%', height: '100%' }"
        >
          <van-nav-bar>
            <template #left>
              <span @click="fromImgBack">返回</span>
            </template>
          </van-nav-bar>
          <div v-for="(item, index) in 6" :key="index" class="gl_my_10" align="center" style="position:relative;">
            <upload-file
              :ref="'ref'+imgUrlKey+index"
              :action="baseUrl + '/api/upload/image'"
              accept=".jpg,.png,.jpeg"
              class-name="wtaImg"
              :file-url="getStaticFileUrl(fileList[index], imgUrlKey)"
              @uploadSuccess="photoSavePositive($event, imgUrlKey, index)"
            >
              <span slot="uploadName" style="font-size: 14px;">点击上传照片</span>
            </upload-file>
            <div class="imgDelWrap" @click="delImg(index)">
              <i class="imgDelete el-icon-delete" />
            </div>
          </div>
        </van-popup>
        <!-- 下拉选择 -->
        <popup-select
          ref="popupSelect"
          :select-data="selectData"
          :default-code="selectDefaultCode"
          :value-key="valueKey"
          @onConfirm="confirmSelectBox"
        />
      </van-form>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { CopyData } from '@/lib';
import UploadFile from '@/viewMobile/components/UploadFile/index';
import PopupSelect from '@/viewMobile/components/PopupSelect';
import { ModTkwChiDanVO } from '@/lib/form/train/enter.js';
import { ModTkwChiDanVO_Rules } from '@/lib/validate/mobile/myCenter';
import {
  api_GET_EventsManagementRegisterId,
  api_PUT_EventsManagementRegisterId,
  api_POST_EventsManagementRegister
} from '@/extend/api/gameswaggerApi/app';
export default {
  components: {
    UploadFile,
    PopupSelect
  },
  data() {
    return {
      isPageLoading: false,
      individualInfo: {},
      createRegisterInput: null,
      vo: new ModTkwChiDanVO(),
      ModTkwChiDanVO_Rules: new ModTkwChiDanVO_Rules(),
      /* 上传照片相关 */
      baseUrl: WEB_CONFIG.VUE_APP_STATIC_FILE_RUL,
      logoDialog: false,
      memberImgDialog: false,
      fileList: [],
      imgListLevel: [], // 级位照片
      imgListDuan: [], // 段位照片
      // 选择器
      selectData: [],
      selectDefaultCode: null,
      valueKey: 'value',
      defaultArea: [],
      defaultDateTime: '',
      popupDateTime: false,
      defaultImgUrl: null,
      imgUrlKey: null
    };
  },
  computed: {
    ...mapState({
      currentUserType: state => state.user.currentUserType,
      dict: state => state.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getIndividualInfo();
      }
    }
  },
  created() {
    this.getDict();
    this.gameId = this.$route.params.id;
    if (this.currentUserType) {
      this.getIndividualInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取个人数据
    getIndividualInfo() {
      if (!this.currentUserType.registerId) return;
      api_GET_EventsManagementRegisterId(
        this.currentUserType.registerId,
        { IncludeGender: true, IncludeIdCardType: true }
      ).then(res => {
        this.individualInfo = res;
        this.vo = res;
        this.formatImgListFromMemberImg(this.vo);
        this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
      }, error => {
        this.$toast.fail(`获取个人信息失败！${error.error.message}`);
      });
    },
    // 将暂存的数组赋值给vo
    getImgData () {
      const _keyData = {
        'ctaBeltLevelImageUrl': this.imgListLevel,
        'ctaBeltDuanImageUrl': this.imgListDuan
      };

      for (const k in _keyData) {
        const ktem = _keyData[k];

        for (let i = 0; i < ktem.length; i++) {
          const item = ktem[i];
          this.createRegisterInput[k + (i + 1)] = item;
        }
      }
    },
    // 根据数据格式化图片数组
    formatImgListFromMemberImg (data) {
      const _keyData = {
        imgListLevel: [
          'ctaBeltLevelImageUrl1',
          'ctaBeltLevelImageUrl2',
          'ctaBeltLevelImageUrl3',
          'ctaBeltLevelImageUrl4',
          'ctaBeltLevelImageUrl5',
          'ctaBeltLevelImageUrl6'
        ],
        imgListDuan: [
          'ctaBeltDuanImageUrl1',
          'ctaBeltDuanImageUrl2',
          'ctaBeltDuanImageUrl3',
          'ctaBeltDuanImageUrl4',
          'ctaBeltDuanImageUrl5',
          'ctaBeltDuanImageUrl6'
        ]
      };

      for (const k in _keyData) {
        const list = _keyData[k];
        const _arr = [];
        for (let i = 0; i < list.length; i++) {
          const item = list[i];
          if (data[item]) {
            _arr.push(data[item]);
            this.vo[item] = '';
          }
        }
        this[k] = _arr;
      }
    },
    // 提交
    submitRefresh() {
      this.createRegisterInput = JSON.parse(JSON.stringify(this.individualInfo));
      CopyData(this.vo, this.createRegisterInput);
      this.getImgData();
      if (this.validateRule()) {
        if (this.currentUserType.registerId) {
          this.updateMemberInfo();
        } else {
          this.addMemberInfo();
        }
      }
    },
    validateRule() {
      // 判断级位或段位有值时，对应的编号和照片是否为空
      if (this.createRegisterInput.ctaBeltLevel) {
        if (!this.createRegisterInput.ctaBeltLevelId || this.createRegisterInput.ctaBeltLevelId === '') {
          this.$toast.fail('中国跆协级位编号不能为空');
          return false;
        }
        if (!this.createRegisterInput.ctaBeltLevelImageUrl1 || this.createRegisterInput.ctaBeltLevelImageUrl1 === '') {
          this.$toast.fail('中国跆协级位照片不能为空');
          return false;
        }
      }
      if (this.createRegisterInput.ctaBeltDuan) {
        if (!this.createRegisterInput.ctaBeltDuanId || this.createRegisterInput.ctaBeltDuanId === '') {
          this.$toast.fail('中国跆协段位编号不能为空');
          return false;
        }
        if (!this.createRegisterInput.ctaBeltDuanImageUrl1 || this.createRegisterInput.ctaBeltDuanImageUrl1 === '') {
          this.$toast.fail('中国跆协段位照片不能为空');
          return false;
        }
      }
      return true;
    },
    // 新增个人信息
    addMemberInfo() {
      // 将空字符串转为Null
      for (const k in this.createRegisterInput) {
        const ktem = this.createRegisterInput[k];
        if (ktem === '') {
          this.createRegisterInput[k] = null;
        }
      }
      api_POST_EventsManagementRegister(this.createRegisterInput).then(() => {
        this.isPageLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$store.dispatch('user/getInfo');
        this.$store.dispatch('user/getCurrentUserType');
        this.$toast.success('操作成功');
      }, error => {
        this.$toast.fail(`${error.error.message}`);
        this.isPageLoading = false;
      });
    },
    // 更新个人信息
    updateMemberInfo() {
      api_PUT_EventsManagementRegisterId(this.currentUserType.registerId, this.createRegisterInput).then(() => {
        this.isPageLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$toast.success('操作成功');
      }, error => {
        this.$toast.fail(`${error.error.message}`);
        this.isPageLoading = false;
      });
    },
    photoSavePositive(fileUrl, type, index) {
      // this.$set(this.vo, this.imgUrlKey, response.tempUrl);
      const _data = this[type];
      this.$set(_data, index, fileUrl.tempUrl);
    },
    // 图片预览
    imagePreview(relativeUrl) {
      this.$imagePreview([this.getStaticFileUrl(relativeUrl)]);
      event.stopPropagation();
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl, code) {
      console.log('relativeUrl', this.fileList);
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return code ? '' : require('@/assets/images/face_default.png');
      }
    },
    // 打开修改照片
    openChangeImg(code) {
      this.fileList = this[code];
      this.defaultImgUrl = this.vo[code];
      this.imgUrlKey = code;
      this.logoDialog = true;
    },
    fromImgBack() {
      this[this.imgUrlKey] = [];
      this[this.imgUrlKey] = this.fileList;
      this.fileList = [];
      this.defaultImgUrl = null;
      // this.imgUrlKey = null;
      this.logoDialog = false;
      for (let i = 0; i < 6; i++) {
        this.$refs['ref' + this.imgUrlKey + i][0].reset();
      }
    },
    // 删除图片
    delImg(index) {
      this[this.imgUrlKey].splice(index, 1);
      for (let i = index; i < 6; i++) {
        this.$refs['ref' + this.imgUrlKey + i][0].init(this[this.imgUrlKey][i]);
      }
    },
    /* ===== select 选择器相关 ===== */
    openSelectBox(code) {
      // 解决某种情况下弹出框非本系统操作关闭之后无法打开
      this.$refs.popupSelect.close();
      this.selectBoxCode = code;
      this.valueKey = 'value';
      this.selectDefaultCode = String(this.vo[code]);
      switch (code) {
        // 级位
        case 'ctaBeltLevel':
          this.selectData = this.dict ? this.dict.dictCtaBeltLevel : [];
          break;
        // 段位
        case 'ctaBeltDuan':
          this.selectData = this.dict ? this.dict.dictCtaBeltDuan : [];
          break;
        default:
          this.selectData = this.dict ? this.dict.dict[code] : [];
          this.selectDefaultCode = this.vo[code];
          break;
      }
      this.$refs.popupSelect.open();
    },
    confirmSelectBox(value) {
      this.vo[this.selectBoxCode] = value.code;
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    goBack() {
      this.$router.push({
        path: `/myCenter${this.gameId && '/' + this.gameId || ''}/individual`
      });
    }
  }
};
</script>

<style>
.wtaImg {
  width: 180px;
  height: 88px;
}
.imgDelWrap {
  position: absolute;
  top: -29px;
  right: 70px;
  width: 60px;
  height: 60px;
  cursor: pointer;
  transform: rotate(45deg);
}
.imgDelete {
  font-size: 18px;
  position: absolute;
  top: 37px;
  left: 21px;
  transform: rotate(-45deg);
  color: rgba(255, 0, 0, 0.8);
}
</style>
